<?php

namespace app\api\controller;

use think\Controller;
use think\facade\Request;

class NameGenerator extends Controller
{
    protected $user_model;
    protected $record_model;

    public function __construct()
    {
      $this->user_model   = new \app\common\model\User();
      $this->record_model   = new \app\common\model\Record();
    }

    /**
     * 名字数据生成
     */
    public function index()
    {
        // try {
            // 1. 用户认证
            $user = $this->authenticateUser();
            if (!$user) {
                return json(['code' => 401, 'msg' => '身份验证失败']);
            }
           
            // 2. 参数验证与获取
            $params = $this->validateAndGetParams();
            if (!$params['success']) {
                return json($params['response']);
            }

            // 3. 构建提示词
            $prompt = $this->buildPrompt($params['data']);

            // 4. 调用AI API
            $apiResponse = $this->callDeepSeekAPI($prompt);
            if (!$apiResponse['success']) {
                return json($apiResponse['response']);
            }

           $generated_content = $apiResponse['data']['choices'][0]['message']['content'];
           $name_data = json_decode($generated_content, true);
            // 6. 保存查询记录
            foreach ($name_data['names'] as $k=>$v) {
               $this->saveQueryRecord($user['id'], $params['data'], $v);
            }
            return json([
                'code' => 200, 
                'msg' => 'success', 
                'data' => $name_data['names']
            ]);

        // } catch (\Exception $e) {
            // 记录异常日志
            // Log::error('姓名生成异常: ' . $e->getMessage());
            // return json(['code' => 500, 'msg' => '服务器内部错误，请稍后重试']);
        // }
    }

    /**
     * 用户认证
     */
    private function authenticateUser()
    {
        $token = request()->header("authorization");
        if (!$token) {
            return false;
        }
        
        return $this->user_model->getOne(['token' => $token], 'id', 'id ASC');
    }

    /**
     * 参数验证与获取
     */
    private function validateAndGetParams()
    {
        $data = [
            'birth_status' => input('post.birth_status/d'),
            'surname' => input('post.surname/s'),
            'gender' => input('post.gender/d'),
            'birth_time' => input('post.birth_time/s'),
            'parents_wish' => input('post.parents_wish/s'),
            'name_format' => input('post.name_format/d'),
            'fixed_words' => input('post.fixed_words/s'),
            'fixed_words_type' => input('post.fixed_words_type/d')
        ];

        // 验证出生状态
        if (!in_array($data['birth_status'], [1, 2])) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '出生状态参数错误']];
        }

        // 验证姓氏
        if (empty($data['surname'])) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '请填写姓氏']];
        }
        
        if (mb_strlen($data['surname'], 'UTF-8') > 2) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '姓氏不能超过2个汉字']];
        }
        
       if ($data['birth_status'] == 1 && empty($data['gender'])) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '请选择性别']];
        }

        // 验证性别（仅当已出生时）
        if ($data['birth_status'] == 1 && !in_array($data['gender'], [1, 2])) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '性别参数错误']];
        }

        // 验证出生时间格式
        if ($data['birth_status'] == 1) {
            if (empty($data['birth_time'])) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '请填写出生时间']];
            }
            $birth_timestamp = strtotime($data['birth_time']);
            if ($birth_timestamp === false || $birth_timestamp > time()) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '出生时间格式错误或不能是未来时间']];
            }
        }else{
            if (empty($data['birth_time'])) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '请填写预计出生时间']];
            }
        }
        if (!preg_match('/^\d{4}-\d{2}-\d{2}-\d{2}$/', $data['birth_time'])) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '出生时间格式错误，请使用年-月-日-时格式']];
        }

        // 验证名字形式
        if (!in_array($data['name_format'], [1, 2, 3])) {
            return ['success' => false, 'response' => ['code' => 100, 'msg' => '名字形式参数错误']];
        }

        // 验证固定文字
        if ($data['name_format'] == 3) {
            if (empty($data['fixed_words'])) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '请填写固定文字']];
            }
            
            if (mb_strlen($data['fixed_words'], 'UTF-8') > 1) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '固定文字不能超过1个汉字']];
            }
            
            if (!in_array($data['fixed_words_type'], [1, 2])) {
                return ['success' => false, 'response' => ['code' => 100, 'msg' => '固定文字类型参数错误']];
            }
        } else {
            $data['fixed_words'] = '';
            $data['fixed_words_type'] = 0;
        }

        return ['success' => true, 'data' => $data];
    }

    /**
     * 构建提示词
     */
    private function buildPrompt($data)
    {
        $prompt = "你是一个专业的起名顾问，精通生辰八字、五行命理、生肖星座、姓名学以及文化寓意。请根据以下信息提供5个不同的名字结果：\n\n";

        $prompt .= "出生状态：" . ($data['birth_status'] == 1 ? "已出生" : "未出生") . "\n";
        $prompt .= "姓氏：{$data['surname']}\n";
        
        if ($data['birth_status'] == 1) {
            $prompt .= "性别：" . ($data['gender'] == 1 ? "男" : "女") . "\n";
            $prompt .= "出生时间：{$data['birth_time']}\n";
        } else {
            $prompt .= "预产期：{$data['birth_time']}\n";
        }

        if (!empty($data['parents_wish'])) {
            $prompt .= "父母期望：{$data['parents_wish']}\n";
        }

        $name_format_text = [1 => "不限", 2 => "单字", 3 => "双字"];
        $prompt .= "名字形式：" . $name_format_text[$data['name_format']] . "\n";

        if ($data['name_format'] == 3 && !empty($data['fixed_words'])) {
            $fixed_words_position = ($data['fixed_words_type'] == 1 ? "中间" : "末尾");
            $prompt .= "固定文字：{$data['fixed_words']}（{$fixed_words_position}）\n";
        }

        $prompt .= "\n请以JSON格式返回一个包含5个名字的数组，每个名字包含以下信息：
[
 {
  \"name_chinese\": \"姓名汉字\",
  \"name_score\": \"名字打分（0-100分）\",
  \"wuxing_analysis\": \"整体五行分析描述\",
  \"wuxing_breakdown\": [
     {\"character\": \"字\", \"wuxing\": \"五行属性\", \"name_pinyin\": \"拼音\"},
     {\"character\": \"字\", \"wuxing\": \"五行属性\", \"name_pinyin\": \"拼音\"}
  ],
  \"meaning\": \"姓名寓意\",
  \"bazi_analysis\": \"八字用字分析\",
  \"shengxiao_analysis\": \"生肖用字分析\",
  \"constellation_analysis\": \"星座分析\",
  \"gender_ratio\": {
     \"male\": \"男性使用比例，仅返回整数\",
     \"female\": \"女性使用比例，仅返回整数\"
  }
 },
 // 再生成4个类似结构...
]";
        return $prompt;
    }

    /**
     * 调用DeepSeek API
     */
    private function callDeepSeekAPI($prompt)
    {
        $api_url = 'https://api.deepseek.com/v1/chat/completions';
        $api_key = config("deepseek.api_key");

        $request_data = [
            'model' => 'deepseek-chat',
            'messages' => [['role' => 'user', 'content' => $prompt]],
            'temperature' => 0.7,
            'max_tokens' => 8192,
            'response_format' => ['type' => 'json_object']
        ];

        $ch = curl_init($api_url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($request_data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $api_key
            ],
            CURLOPT_TIMEOUT => 0,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            return [
                'success' => false, 
                'response' => ['code' => 500, 'msg' => 'AI服务请求失败: ' . $error]
            ];
        }

        if ($http_code != 200) {
            return [
                'success' => false, 
                'response' => ['code' => 500, 'msg' => 'AI服务响应异常']
            ];
        }

        return ['success' => true, 'data' => json_decode($response, true)];
    }

    /**
     * 解析和验证API响应
     */
    private function parseAndValidateResponse($apiResponse)
    {
        if (!isset($apiResponse['choices'][0]['message']['content'])) {
            return ['success' => false, 'response' => ['code' => 500, 'msg' => 'AI响应格式错误']];
        }

        $generated_content = $apiResponse['choices'][0]['message']['content'];
        $name_data = json_decode($generated_content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return ['success' => false, 'response' => ['code' => 500, 'msg' => '名字生成格式错误']];
        }

        // 检查是否为数组格式
        if (!is_array($name_data)) {
            return ['success' => false, 'response' => ['code' => 500, 'msg' => '名字生成数据格式错误，应为数组']];
        }

        // 检查数组长度
        if (count($name_data) < 5) {
            return ['success' => false, 'response' => ['code' => 500, 'msg' => '名字生成数量不足，请重试']];
        }

        $valid_names = [];
        $required_fields = ['name_chinese', 'name_score', 'wuxing_analysis', 'meaning'];
        
        foreach ($name_data as $index => $name) {
            // 验证必要字段是否存在
            $valid = true;
            foreach ($required_fields as $field) {
                if (!isset($name[$field])) {
                    $valid = false;
                    break;
                }
            }
            
            if (!$valid) {
                continue;
            }

            // 验证姓名格式
            if (!preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $name['name_chinese'])) {
                continue;
            }

            // 验证分数范围
            if (!is_numeric($name['name_score']) || $name['name_score'] < 0 || $name['name_score'] > 100) {
                continue;
            }

            $valid_names[] = $name;
        }

        // if (count($valid_names) < 3) { // 允许部分名字验证失败，但至少要有3个有效名字
        //     return ['success' => false, 'response' => ['code' => 500, 'msg' => '有效名字数量不足，请重试']];
        // }

        return ['success' => true, 'data' => $valid_names];
    }

    /**
     * 保存查询记录
     */
    private function saveQueryRecord($user_id, $params, $name_data)
    {
        $query_data = [
            'user_id' => $user_id,
            'ip' => Request::ip(),
            'create_time' => time(),
            'update_time' => time(),
            'surname' => $params['surname'],
            'gender' => $params['gender'],
            'birth_status' => $params['birth_status'],
            'birth_time' => $params['birth_time'],
            'name_format' => $params['name_format'],
            'fixed_words' => $params['fixed_words'],
            'fixed_words_type' => $params['fixed_words_type'],
            'parents_wish' => $params['parents_wish'],
            'name_chinese' => $name_data['name_chinese'],
            'name_score' => $name_data['name_score']
        ];

        return $this->record_model->addData($query_data);
    }
}